import React, { useEffect, useState } from "react";
import { modalPropsType } from "@/constants/types";
import { Modal, Form, Input, Tree, Checkbox } from "antd";
import { DataNode, TreeProps } from "antd/es/tree";
import { fetchRoleFunctionTree } from '../../services';
import { compareArr } from "@/utils/util";
import { FUNCTION_LEVEL } from "@/constants";
import './index.less';

const {Item} = Form;
const rules = [{required: true, message: '此项必填'}];
const labelCol = {span: 4};

// 自定义节点头
const NodeTitle = ({ node, allChecked = [], onChange, disabled}: {node: any, allChecked: string [], onChange: any, disabled: boolean}) => {
  const [checked, setChecked] = useState<string[]>([]);

  const handleChange = (values: string []) => {
    // 先移除选中的功能中当前节点的功能 再将values新增进去
    const arr = allChecked.filter(v => !node?.functions?.some((s: {name: string, id: string}) => s.id === v));
    const newChecked = arr.concat(values);
    setChecked(newChecked);
    onChange(newChecked)
  }

  useEffect(() => {
    if (!compareArr(allChecked, checked)) {
      setChecked([...allChecked]);
    }
  }, [JSON.stringify(allChecked)]);
  
  return (
    <div className="role-node">
      <div className="title">{node?.name}</div>
      {
        node?.level === FUNCTION_LEVEL && node?.functions?.length > 0 && (
          <div className="options" onClick={e => e.stopPropagation()}>
            <Checkbox.Group disabled={disabled} value={checked} onChange={handleChange} options={node?.functions?.map((v: {name: string, id: string}) => ({label: v?.name, value: v?.id}))} />
          </div>
        )
      }
    </div>
  );
}

const RoleUpdateModal = ({visible, onCancel, onSubmit, currentRow, loading, title, disabled}: modalPropsType) => {
  const [form] = Form.useForm();
  const [checkedFunctions, setCheckedFunctions] = useState<string[]>([]);
  const [checkedNodes, setCheckedNodes] = useState<string[]>([]);
  const [treeData, setTreeData] = useState<DataNode []>([]);
  const [expandedKeys, setExpandedKeys] = useState<string []>([]);

  const fetchRoleFunctionTreeApi = async (id: string) => {
    const res = await fetchRoleFunctionTree(id);
    if (res?.code === '0' && res?.data?.length > 0) { 
      // 选中的功能
      let functionCheckedList: string [] = [];
      // 选中的树节点
      let treeCheckedList: string [] = [];
      // 所有展开的节点
      let expandedList: string [] = [];

      const mapTree = (arr: any []) => {
        arr.forEach(element => {
          expandedList.push(element.id);
          // 功能所在的level值为FUNCTION_LEVEL
          if (element.level === FUNCTION_LEVEL) {
            functionCheckedList = functionCheckedList.concat((element?.functions || []).filter((v: {id: string, have: boolean}) => v.have).map((v: {id: string, have: boolean}) => v.id));
          } else if (element.children?.length > 0){
            mapTree(element.children);
          }
          if (!element.children?.length && element.have) {
            treeCheckedList.push(element.id);
          }
        });
      }
      // 递归枚举树节点
      mapTree(res?.data);
      setTreeData(res?.data);
      setCheckedFunctions(functionCheckedList);
      setCheckedNodes(treeCheckedList);
      setExpandedKeys(expandedList);
    }
  }


  const onCheck: TreeProps['onCheck'] = (checkedKeys) => {
    setCheckedNodes(checkedKeys);
  };
  const onExpand = (keys: string []) => {
    setExpandedKeys(keys);
  }

  const functionsChange = (vals: string[]) => {
    setCheckedFunctions(vals);
  }

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      ...res,
      id: currentRow?.id,
      functionIds: checkedFunctions,
      pageIds: checkedNodes
    });
  }

  useEffect(() => {
    if(currentRow?.id) {
      form.setFieldsValue({
        roleName: currentRow?.roleName,
        remark: currentRow?.remark
      });
    }
    fetchRoleFunctionTreeApi(currentRow?.id);
  }, [JSON.stringify(currentRow)])

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      maskClosable={false}
      confirmLoading={loading}
      width="700px"
      footer={disabled ? false: undefined}
    >
      <Form form={form} labelCol={labelCol} className="form-wrapper">
        <Item name="roleName" label="角色中文名称" rules={rules}>
          <Input disabled={disabled} />
        </Item>
        {/* <Item name="" label="角色英文名称" rules={rules}>
          <Input disabled={disabled} />
        </Item> */}
        <Item name="remark" label="角色描述">
          <Input disabled={disabled} />
        </Item>
      </Form>
      <div className="tree-heder">
        <div className="title">菜单权限</div>
        <div className="title">按钮权限</div>
      </div>
      <Tree
        checkable={!disabled}
        expandedKeys={expandedKeys}
        checkedKeys={checkedNodes}
        onCheck={onCheck}
        onExpand={onExpand}
        treeData={treeData}
        fieldNames={{
          title: "name",
          key: "id",
          children: "children"
        }}
        titleRender={(node) => <NodeTitle onChange={functionsChange} node={node} allChecked={checkedFunctions} disabled={disabled} />}
      />
    </Modal>
  );
}
export default RoleUpdateModal;